import express from "express";
import cors from "cors";
import axios from "axios";
import dotenv from "dotenv";
import { fileURLToPath } from "url";
import { dirname, join } from "path";
import { env } from "process";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// 加载环境变量
dotenv.config({ path: join(__dirname, ".env") });

const HUGGING_FACE_API_KEY = env.VITE_HUGGINGFACE_API_KEY;

const app = express();
const port = 3000;

app.use(cors());
app.use(express.json());

const SUPPORTED_MODELS = {
  "zh-en": "Helsinki-NLP/opus-mt-zh-en",
  "en-zh": "Helsinki-NLP/opus-mt-en-zh",
  "ja-en": "Helsinki-NLP/opus-mt-ja-en",
  "en-ja": "Helsinki-NLP/opus-mt-en-ja",
  "zh-ja": "Helsinki-NLP/opus-mt-zh-ja",
  "ja-zh": "Helsinki-NLP/opus-mt-ja-zh",
};

app.post("/translate", async (req, res) => {
  const { modelName, text } = req.body;

  console.log("Translation request:", { modelName, text });

  try {
    if (!HUGGING_FACE_API_KEY) {
      throw new Error("未设置 Hugging Face API 密钥");
    }

    if (!SUPPORTED_MODELS[modelName]) {
      throw new Error(`不支持的翻译模型: ${modelName}`);
    }

    console.log("Sending request to Hugging Face API...");
    const response = await axios.post(
      `https://api-inference.huggingface.co/models/${SUPPORTED_MODELS[modelName]}`,
      { inputs: text },
      {
        headers: {
          Authorization: `Bearer ${HUGGING_FACE_API_KEY}`,
          "Content-Type": "application/json",
        },
      }
    );

    if (
      !response.data ||
      !Array.isArray(response.data) ||
      response.data.length === 0
    ) {
      throw new Error("API返回的数据格式不正确");
    }

    console.log("Received response from Hugging Face API");
    res.json(response.data);
  } catch (error) {
    console.error("Translation error details:", {
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
      message: error.message,
    });

    res.status(500).json({
      error: "翻译服务出错",
      details: error.response?.data || error.message,
      modelName: modelName,
    });
  }
});

app.get("/health", (req, res) => {
  res.json({
    status: "ok",
    apiKeySet: !!HUGGING_FACE_API_KEY,
    supportedModels: Object.keys(SUPPORTED_MODELS),
  });
});

app.listen(port, () => {
  console.log(`Translation server running at http://localhost:${port}`);
  console.log("Environment check:", {
    apiKeySet: !!HUGGING_FACE_API_KEY,
    supportedModels: Object.keys(SUPPORTED_MODELS),
  });
});
